<?php

class  Customer_model extends CI_Model
{
    public function __construct()
    {
        $this->load->database();
        $this->load->helper("url");
    }

    // 客户短信发送密码计数 cj
    public function sms_send_count($manager_id,$customer_id)
    {
        $query = $this->db->get_where('send_password_count',array('manager_id'=>$manager_id,'customer_id'=>$customer_id,'date'=>date("Y-m-d")));
        $res = $query->row_array();
        if($res)
        {
            return array('id'=>$res['id'],'count'=>$res['count']);
        }
        // 新增一条
        $data['manager_id'] = $manager_id;
        $data['customer_id'] = $customer_id;
        $data['count'] = 0;
        $data['date'] = date("Y-m-d");
        $string = $this->db->insert_string("send_password_count",$data);
        $bool = $this->db->query($string);
        if ($bool) {
            $insert_id = $this->db->insert_id();
            return array('id'=>$insert_id,'count'=>0);
        }else{
            return false;
        }

    }

    // 客户短信发送密码增加一条 cj
    public function sms_send_add($sms_id)
    {
        $sql = "update send_password_count set count=count+1 where id = ".$sms_id;
        return $this->db->query($sql);
    }


    // 更新客户基础信息 cj
    public function update_customer($id,$data){
        if ($id && $data){
            if($data['customer_name']){
               //获取客户
                $manager = $this->db->where(["id"=>$id])->get("customer")->row_array();
                if($data['customer_name']!=$manager['customer_name']){
                    //如果是默认图片
                    if(strstr($manager['pic_path'], $this->config->item("upload_url"))){
                        $data['pic_path'] = $this->create_pic($data['customer_name']);
                    }
                }
            }
            $string = $this->db->update_string("customer",$data,array('id'=>$id));
            $bool = $this->db->query($string);
            return $bool;
        }else{
            return false;
        }
    }

    // 获取客户总订单列表（客户详情使用） cj
    public function customer_order_list($data)
    {
        if(!$data['customer_id'] && is_numeric($data['customer_id'])
            && !$data['manager_id'] && is_numeric($data['manager_id']) )
        {
            return false;
        }
        $customer_id = $data['customer_id'];
        $manager_id = $data['manager_id'];

        $sql = "SELECT
                    co.order_date,
                    co.order_bn,
                    co.id,
                    co.order_status,
                    co.order_money,
                    co.product_count
                FROM
                    customer_order co
                INNER JOIN customer c ON c.id = co.customer_id
                AND c.manager_id = co.manager_id
                WHERE
                    co.manager_id = ".$manager_id."
                           and
                    co.customer_id = ".$customer_id."
                ORDER BY co.order_date DESC";

        $sql_count = "SELECT
                   count(1) as order_count,
                   SUM(order_money) as total_money
                FROM
                    customer_order co
                INNER JOIN customer c ON c.id = co.customer_id
                AND c.manager_id = co.manager_id
                WHERE
                    co.manager_id = ".$manager_id."
                    and
                    co.customer_id = ".$customer_id."
                ORDER BY co.order_date DESC";

        // 查询订单数量和总价
        $order_count = 0;
        $total_money = 0;
        $re = $this->db->query($sql_count)->result_array();
        if($re)
        {
            $order_count = $re[0]['order_count'];
            $total_money = $re[0]['total_money'];
        }
        if(!$order_count)
        {
            return false;
        }
        // 查询会员信息
        $sql_member = "SELECT
                            c.adjustments,
                            c.discount,
                            c.id as customer_id
                        FROM
                            customer AS c
                        WHERE
                            id = ".$customer_id;
        $re_member = $this->db->query($sql_member)->result_array();

        $page = $data['page']?(int)$data['page']:1;
        $psize = $data['psize']?(int)$data['psize']:3;
        $limit_from = ($page-1)*$psize;
        $sql.=" LIMIT ".$limit_from.",".$psize;
        $res = $this->db->query($sql)->result_array();

        if($res)
        {
            return array('order_list'=>$res,'order_count'=>$order_count,'total_money'=>$total_money,'member_info'=>$re_member[0]);
        }
        return false;

    }

    // 获取客户订单列表 cj
    public function customer_order_detail_list($data)
    {
        if(!$data['customer_id'] && is_numeric($data['customer_id'])
            && !$data['manager_id'] && is_numeric($data['manager_id']) )
        {
            return false;
        }
        $customer_id = $data['customer_id'];
        $manager_id = $data['manager_id'];

        $sql = "SELECT
                    co.order_date,
                    co.order_bn,
                    co.id order_id,
                    co.order_status,
                    co.order_money,
                    co.product_count,
                    co.commission_status,
                    co.commission_total
                FROM
                    customer_order co
                INNER JOIN customer c ON c.id = co.customer_id
                AND c.manager_id = co.manager_id
                WHERE
                    co.manager_id = ".$manager_id."
                           and
                    co.customer_id = ".$customer_id."
                ORDER BY co.order_date DESC";

//        $sql_count = "SELECT
//                   count(*) as order_count,
//                   SUM(order_money) as total_money
//                FROM
//                    customer_order co
//                INNER JOIN customer c ON c.id = co.customer_id
//                AND c.manager_id = co.manager_id
//                WHERE
//                    co.manager_id = ".$manager_id."
//                    and
//                    co.customer_id = ".$customer_id."
//                ORDER BY co.order_date DESC";

        // 查询订单数量和总价
//        $order_count = 0;
//        $total_money = 0;
//        $re = $this->db->query($sql_count)->result_array();
//        if($re)
//        {
//            $order_count = $re[0]['order_count'];
//            $total_money = $re[0]['total_money'];
//        }
//        if(!$order_count)
//        {
//            return false;
//        }
        // 查询会员信息
        $sql_member = "SELECT
                            c.adjustments,
                            c.discount,
                            c.id as customer_id,
                            c.customer_tel,
                            c.pic_path,
                            c.customer_name
                        FROM
                            customer AS c
                        WHERE
                            id = ".$customer_id;
        $re_member = $this->db->query($sql_member)->result_array();

        $page = $data['page']?(int)$data['page']:1;
        $psize = $data['psize']?(int)$data['psize']:10;
        $limit_from = ($page-1)*$psize;
        $sql.=" LIMIT ".$limit_from.",".$psize;
        $res = $this->db->query($sql)->result_array();

        if(is_array($res))
        {
            $query_ar = '';
            foreach ($res as $r)
            {
                $query_ar[$customer_id][] = $r['order_bn'];
            }
            $url = $this->config->item("shop_base_url")."citymanagerapi/get_order_info/";
            $data1['key'] = md5_key();
            $data1['orders'] =json_encode($query_ar);
            $get_data = curl_request($url,$data1);
            $get_data = json_decode($get_data);
            if ($get_data->code==200){
                foreach ($get_data->data as $dinfo)
                {
                    $msinfo[$dinfo->order_sn]['order_status_cn'] = $dinfo->order_status_cn;
                    // 处理商品信息
                    foreach ($dinfo->product_info as $k => $pinfo)
                    {
                        $msinfo[$dinfo->order_sn]['product_info'][$k]['product_id'] = $pinfo->product_id;
                        $msinfo[$dinfo->order_sn]['product_info'][$k]['product_name'] = $pinfo->product_name;
                        $msinfo[$dinfo->order_sn]['product_info'][$k]['product_price'] = $pinfo->product_price;
                        $msinfo[$dinfo->order_sn]['product_info'][$k]['product_num'] = $pinfo->product_num;
                        $msinfo[$dinfo->order_sn]['product_info'][$k]['default_image'] = $pinfo->default_image;
                        $msinfo[$dinfo->order_sn]['product_info'][$k]['product_spec'] = $pinfo->product_spec;
                        $msinfo[$dinfo->order_sn]['product_info'][$k]['refund'] = $pinfo->refund;
                    }
                    $msinfo[$dinfo->order_sn]['shipping_amount'] = $dinfo->shipping_amount;
                    $msinfo[$dinfo->order_sn]['final_amount'] = $dinfo->final_amount;
                    // 用接口订单总价 表中数据有订单的不对的。 cj
                    $msinfo[$dinfo->order_sn]['order_money'] = $dinfo->final_amount;
                }
                if($msinfo)
                {
                    foreach ($res as $k => $r)
                    {
                        $res[$k]['product_info'] = $msinfo[$r['order_bn']]['product_info']?$msinfo[$r['order_bn']]['product_info']:array();
                        $res[$k]['shipping_amount'] = $msinfo[$r['order_bn']]['shipping_amount']?$msinfo[$r['order_bn']]['shipping_amount']:0;
                        $res[$k]['order_status'] = $msinfo[$r['order_bn']]['order_status_cn']?$msinfo[$r['order_bn']]['order_status_cn']:$r['order_status'];
                        // 用接口订单总价 表中数据有订单的不对的。 cj
                        $res[$k]['order_money'] = $msinfo[$r['order_bn']]['order_money'];
                    }
                }
            }
        }



        if($res)
        {
            return array('order_list'=>$res,'member_info'=>$re_member[0]);
        }
        return false;


    }

    // 获取客户账户详情 cj
    public function get_customer_info($data)
    {
        if(!$data['customer_id'] && is_numeric($data['customer_id']))
        {
            return false;
        }
        $query = $this->db->get_where('customer',array('id'=>$data['customer_id']));
        $res = $query->row_array();
        if(is_array($res))
        {
            unset($res['password']);
        }else{
            return false;
        }
        //查询账号
        $mg = $this->db->where(["id"=>$res['manager_id']])->get("manager")->row_array();
        // 所属经理name
        $res['manager_name'] = $mg['name'];
        // 如果没有客户姓名那么用经理name
        $res['account'] = $mg['name'];

        $url = $this->config->item("shop_base_url")."citymanagerapi/customer_detail/";
        $data1['key'] = md5_key();
        $data1['id'] =$data['customer_id'];
//        $data1['id'] =352;
        $get_data = curl_request($url,$data1);
        $get_data = json_decode($get_data);
        if ($get_data->code==200){
            $res['login_num'] = $get_data->data->login_num?$get_data->data->login_num:0;
            $res['invoice_info'] = $get_data->data->invoice_info;
            if($get_data->data->account)
            {
                $res['account'] = $get_data->data->account;
            }
            // 测试cj
//            $res['invoice_info'] = array(array('invoice_detail'=>'增值税发票',
//                                               'invoice_company'=>'发票抬头啊',
//                                               'invoice_identify'=>'12312312312312312',
//                                               'invoice_address'=>'上海路sss区222号',
//                                               'invoice_tel'=>'18558595859',
//                                               'invoice_bank'=>'中国银行',
//
//            ));
            $res['address_info'] = $get_data->data->address_info;
            // 测试cj
//            $res['address_info'] = array(array('addr_id'=>'1','consignee'=>'收货人晓明','region_name'=>'江苏省无锡市','address'=>'神马街道','zipcode'=>'214000','phone_tel'=>'0510-2222222','phone_mob'=>'13949494949'));
        }else{
            return false;
        }
        return $res;

    }


    function create($data=null){
        if ($data){
            $string = $this->db->insert_string("customer",$data);
            $bool = $this->db->query($string);
            if ($bool){
                $insert_id =$this->db->insert_id();
                $insert_his = array(
                    "customer_id"=>$insert_id,
                    "manager_id"=>$data['manager_id'],
                    "start_time"=>date("Y-m-d h:i:s")
                );
                $his_string = $this->db->insert_string("customer_bind_history",$insert_his);
                $bool = $this->db->query($his_string);
                return $insert_id;
            }else{
                return $bool;
            }
        }else{
            return false;
        }

    }

    function upd_info($where=null,$data){
        if ($data && $where){
            $string = $this->db->update_string("customer",$data,$where);

            $bool = $this->db->query($string);
            return $bool;
        }else{
            return false;
        }
    }
    //是否重复
    function is_has_pwd($manager_id = 0,$pwd = 0){
        $rs = $this->db->where(array("manager_id"=>$manager_id,"password"=>$pwd))->get("customer")->result_array();
        if ($rs){
            return true;
        }else{
            return false;
        }
    }

    function get_pwd($manager_id =0,$length=6,$pwd=""){
        //获取该用户创建的所有密码
        if (!$pwd){
            $pwd = rand(pow(10,($length-1)), pow(10,$length)-1);
        }
        if ($this->is_has_pwd($manager_id,$pwd)){
          $pwd = $this->get_pwd($manager_id,6,$pwd);
        }
        return $pwd;
    }


    //产生头像
    function create_pic($str)
    {
        if ($str) {
            $first_str = strtolower(getFirstCharter($str));
            return $this->config->item("upload_url") . "customer_pic/" . $first_str . ".png";
        } else {
            return "";
        }
    }
        //验证客户信息
        function validate($data1) {
            $arr = $data1;
            if($arr['customer_email']){
                if(!is_email($arr['customer_email'])){
                    $data['status'] = "fail";
                    $data['msg'] = "邮箱格式错误";
                    $data['data'] = "";
                    return $data;
                }
            }
            if($arr['customer_tel']){
                if(!is_mobile($arr['customer_tel'])){
                    $data['status'] = "fail";
                    $data['msg'] = "手机格式错误";
                    $data['data'] = "";
                    return $data;
                }
            }
            if($arr['customer_name']){
                if(!check_name($arr['customer_name'])){
                    $data['status'] = "fail";
                    $data['msg'] = "姓名必须是中文和字母,不能超过10位!";
                    $data['data'] = "";
                    return $data;
                }
            }
            $data['status'] = "success";
            return $data;

        }






}